package ua.kpi.apolonov.factories;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import ua.kpi.apolonov.IO.ExternalFileService;
import ua.kpi.apolonov.databases.StaticDatabase;
import ua.kpi.apolonov.parsers.Parsers;
import ua.kpi.apolonov.questions.Question;

/**
 * Factory for the production questions from external resources
 * @version 1.4 18.03.2013
 * @author Yegor Apolonov
 */

public class FileQuestionsFactory extends QuestionsFactory{
	
	private List<Question> questions = new ArrayList<Question>();
	private Parsers parser = new Parsers();
	private String FILE_NAME = "src/ua/kpi/apolonov/databases/FileDatabase.txt"; 
	private ExternalFileService fileReader = new ExternalFileService(FILE_NAME);	
		
	public FileQuestionsFactory() {
		initializeQuestions();
	}
	
	public FileQuestionsFactory(String fileName) {
		fileReader = new ExternalFileService(fileName);
		initializeQuestions();
	}
	
	@Override
	public List<Question> retrieveQuestions() {
		List<Question> cloneQuestions = new ArrayList<Question>(); 
		try {
			for(Question question : questions){
				cloneQuestions.add(question.clone());
			}
		} catch (CloneNotSupportedException e) {
			System.err.println(e);
		}
		return cloneQuestions;
	}
	
	private void initializeQuestions() {
		try {
			String[] questionStructure = fileReader.readExternalFile();
			for(int questionNumber = 0; questionNumber < questionStructure.length; questionNumber++) {
				String[] detailsOfQuestion = parser.parseFileLine(questionStructure[questionNumber]);
				questions.add(parser.parseFileQuestion(detailsOfQuestion));
			}
			
		} catch(IOException e) {
			System.err.println("Внешняя файловая база данных сейчас недоступна:(\n" + 
							   "Загружается дефолтная база данных:)");
			try {
				for(Question question : new StaticDatabase()){
					questions.add(question.clone());
				}
			} catch(CloneNotSupportedException exception) {
				System.err.println(exception);
			}
		}
	}
}
